package com.lin.generator.controller;

import com.lin.generator.domain.GenTable;
import com.lin.generator.domain.message.ResponseResult;
import com.lin.generator.service.IGenTableColumnService;
import com.lin.generator.service.IGenTableService;
import com.lin.generator.util.Convert;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 代码生成 操作处理
 * 
 * @author linjl
 */
@Api(tags = "代码生成")
@RestController
@RequestMapping("/gen")
public class GenController
{
    @Autowired
    private IGenTableService genTableService;

    @Autowired
    private IGenTableColumnService genTableColumnService;


    /**
     * 查看数据库中有哪些表
     * @return
     */
    @ApiOperation("查看数据库中有哪些表")
    @GetMapping("/listTables")
    public ResponseResult dataList(@ApiParam("表名") @RequestParam(required = false) String tableName)
    {
        GenTable genTable = new GenTable();
        genTable.setTableName(tableName);
        List<GenTable> list = genTableService.selectDbTableList(genTable);
        return ResponseResult.success(list);
    }

    /**
     * 批量生成代码
     */
    @ApiOperation("批量生成代码")
    @GetMapping("/batchGenCode")
    public void batchGenCode(HttpServletResponse response, String tables) throws IOException
    {
        String[] tableNames = Convert.toStrArray(tables);

        // 生成代码
        byte[] data = genTableService.downloadCode(tableNames);
        genCode(response, data);
    }

    @ApiOperation("保存要生成的表信息和列信息")
    @PostMapping("/saveTable")
    public ResponseResult importTableSave(String tables)
    {
        String[] tableNames = Convert.toStrArray(tables);
        // 查询表信息
        List<GenTable> tableList = genTableService.selectDbTableListByNames(tableNames);
        // 保存要生成的表信息和列信息
        genTableService.importGenTable(tableList);
        return ResponseResult.success();
    }

    /**
     * 生成zip文件
     */
    private void genCode(HttpServletResponse response, byte[] data) throws IOException
    {
        response.reset();
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment; filename=\"generatedCode.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }
}